<?php if (!defined('BASEPATH')) exit('No direct access allowed.');

/**
 * 用户验证类
 */
class User_auth_service extends MY_Service {

    protected $_config = array(); //配置信息

    public function __construct() {
        parent::__construct();

        //加载配置
        $this->load->config('auth', true);
        $this->_config = &$this->config->item('auth');

        //加载表单验证类
        $this->load->library('form_validation');
        //加载认证语言类
        $this->lang->load('auth');
        //用户注册验证
        //$this->load->service('user/validator/user_validator');

        log_message('debug', 'User_auth_service Class Initialized');
    }

    ################################ 登陆 ################################

    /**
     * 是否登陆判断
     *
     * @return int 用户UID
     */
    public function is_login() {
        static $login_uid;
        if (isset($login_uid)) return $login_uid;

        if ($ci_loginuser = $this->input->cookie('ci_loginuser')) {
            $ci_loginuser = explode("\t", Utility::decode($ci_loginuser));
            if (count($ci_loginuser) == 2) {
                list($uid, $hash_password) = $ci_loginuser;
                if (is_numeric($uid)) $login_uid = $uid;
            }
        } else {
            $login_uid = 0;
            $hash_password = '';
        }

        return $login_uid;
    }

    /**
     * 获取用户登陆信息
     */
    public function get_login_user() {
        if ($uid = $this->is_login()) {
            $this->load->service('user/bo/user_bo');
            return $this->user_bo->init($uid);
        } else {
            return array();
        }
    }

    /**
     * 用户登录
     *
     * @param string $identity 用户登录的帐号
     * @param string $password 用户登录的密码
     * @param boolean $remember 是否记住用户
     * @param string $safe_question 安全问题
     * @param string $safe_answer 安全问题答案
     * @return boolean|int
     */
    public function login($identity, $password, $remember = false, $safe_question = null, $safe_answer = '') {
        if (empty($identity) || empty($password)) {
            return $this->error->set_error('账号或密码不能为空');
        }

        //获取登陆用户信息
        $user = $this->get_user_by_loginway($identity);

        //如果在锁定时间内
        if ($this->is_time_locked_out()) {
            return $this->error->set_error('尝试登陆超时限制次数 稍后尝试');
        }

        //如果密码相等
        if ($user && $this->hash_password($password, $user['salt']) === $user['password']) {
            //如果用户还没有激活(验证)
            if ($user['status'] == 0) {
                return $this->error->set_error('用户还未激活');
            }
            //记录sessions
            return $this->set_login_cookie($user, $remember);
        } else {
            $this->increase_login_attempt();
            return $this->error->set_error('用户账号或密码错误');
        }
    }

    /**
     * 获取登陆用户信息
     * 根据登陆方式: uid, username, email, mobile
     *
     * @param string $identity 用户登录的帐号
     * @return array
     */
    public function get_user_by_loginway($identity) {
        //手机号码登录
        if ($this->form_validation->is_mobilephone($identity)) {
            //TODO:手机验证
            return array();
        }
        //UID登录
        if (is_numeric($identity)) {
            return $this->get_user_by('uid', $identity);
        }
        //email登录
        if ($this->form_validation->valid_email($identity)) {
            return $this->get_user_by('email', $identity);
        }
        //用户名登录
        return $this->get_user_by('username', $identity);
    }

    /**
     * 设置用户登陆标识
     *
     * @param array $user
     * @param string $remember 是否记住用户
     * @return bool
     */
    public function set_login_cookie($user, $remember) {
        $str = Utility::encode($user['uid'] . "\t" . Utility::get_pwd_code($user['password']));
        $this->input->set_cookie('ci_loginuser', $str, $remember ? 86400 * 365 : 0);

        //清除失败登陆次数
        $this->clear_login_attempt();
        //更新登陆记录
        $this->update_last_login($user);

        return true;
    }

    /**
     * 是否在锁定时间内
     *
     * @return bool
     */
    public function is_time_locked_out() {
        $is_exceeded = $this->is_max_login_attempt_exceeded();
        $last_time = $this->get_last_login_attempt_time();
        return $is_exceeded && $last_time > TIMESTAMP - $this->_config['lockout_time'];
    }

    /**
     * 是否超过了最大尝试登陆次数
     *
     * @return boolean
     **/
    public function is_max_login_attempt_exceeded() {
        if ($this->_config['max_login_attempt'] > 0) {
            $num = $this->get_login_attempt_num();
            return $num >= $this->_config['max_login_attempt'];
        }
        return false;
    }

    ################################ 退出 ################################

    /**
     * 用户退出
     */
    public function logout() {
        return $this->input->set_cookie('ci_loginuser', '', -1);
    }

    ################################ 注册 ################################

    /**
     * 用户注册
     *
     * @param string $username 用户名称
     * @param string $password 用户密码
     * @param string $email 用户邮箱
     * @param array $additional_data 附加数据
     * @return int $uid
     */
    public function register($username, $password, $email, $additional_data = array()) {
        if (($error = $this->auth->check_default_group()) instanceof Error) {
            return $error;
        }
        if (($error = $this->auth->check_ip()) instanceof Error) {
            return $error;
        }
        //验证用户名
        if (($error = $this->check_username($username)) instanceof Error) {
            return $error;
        }
        //验证密码
        if (($error = $this->check_password($password, $username)) instanceof Error) {
            return $error;
        }
        //验证邮箱
        if (($error = $this->check_email($email)) instanceof Error) {
            return $error;
        }

        $uid = null;
        //UCenter是否启用
        if ($this->_config['enable_ucenter']) {
            //加载UCenter
            $this->load->library('uc/uc_api');
            $uc_uid = $this->uc_api->user_register($username, $password, $email);
            if ($uc_uid < 0) {
                return $this->error->set_error($this->uc_api->errors($uid));
            }
            $uid = $uc_uid;
        }

        //用户数据入库
        $uid = $this->add_user($uid, $username, $password, $email);
        return $this->after_register($uid);
    }

    /**
     * 完成注册后执行
     *
     * @param int $uid
     * @return array 用户信息
     */
    public function after_register($uid) {
        //用户扩展表数据入库
        $this->add_user_data($uid);
        $this->add_user_info($uid);

        //同一IP注册次数限制入库
        $this->increase_register_security();
        //清除过期同一IP注册次数限制
        $this->clear_register_security();

        return $this->get_user_by('uid', $uid);
    }

    /**
     * 检查默认用户组是否已经设置
     * 注册页面调用
     */
    public function check_default_group() {
        //注册激活用户默认用户组
        $activation_gid = $this->_config['default_group_activation'];
        //注册未激活用户默认用户组
        $unactivation_gid = $this->_config['default_group_unactivation'];
        //如果默认用户组没有设置
        if ((!$activation_gid or !$unactivation_gid)) {
            return $this->error->set_error('AUTH:register_not_set_default_usergroup');
        }
        return true;
    }

    /**
     * 检测是否规定时间内同一IP将无法进行多次注册
     * 注册页面调用
     *
     * @return true|Error
     */
    public function check_ip() {
        $hour = $this->_config['register_limit_hour'];
        if ($hour && $hour > 0) {
            $row = $this->get_register_security();
            if ($row && TIMESTAMP - $row['last_time'] < $hour * 3600) {
                return $this->error->set_error('AUTH:register_cannot_repeat', array('{hour}' => $hour));
            }
        }
        return true;
    }

    /**
     * 验证用户名
     *
     * @param string $username
     * @return boolean
     */
    public function check_username($username) {
        //用户名是否为空
        if (!$this->check_username_empty($username)) {
            return $this->error->set_error('AUTH:username_empty');
        }
        //用户名长度是否错误
        if (!$this->check_username_length($username)) {
            $min = $this->_config['min_username_length'];
            $max = $this->_config['max_username_length'];
            return $this->error->set_error('AUTH:username_length_error', array('min' => $min, 'max' => $max));
        }
        //检查用户名格式
        if (!$this->check_username_format($username)) {
            $min = $this->_config['min_username_length'];
            $max = $this->_config['max_username_length'];
            return $this->error->set_error('AUTH:username_has_illegal_char', array('min' => $min, 'max' => $max));
        }
        //检查用户名是否禁用
        if (!$this->check_username_ban($username)) {
            return $this->error->set_error('AUTH:username_has_ban_char');
        }
        //UC检查用户名
        if ($this->_config['enable_ucenter']) {
            $this->load->library('uc/uc_api');
            $uc_result = $this->uc_api->user_checkname($username);
            if ($uc_result == -1) {
                $min = $this->_config['min_username_length'];
                $max = $this->_config['max_username_length'];
                return $this->error->set_error('AUTH:username_has_illegal_char', array('min' => $min, 'max' => $max));
            } elseif ($uc_result == -2) {
                return $this->error->set_error('AUTH:username_has_ban_char');
            } elseif ($uc_result == -3) {
                return $this->error->set_error('AUTH:username_already_exists');
            }
        }

        return true;
    }

    /**
     * 检查用户名是否为空
     *
     * @param string $username
     * @return boolen
     */
    public function check_username_empty($username) {
        return $this->form_validation->required($username);
    }

    /**
     * 检查用户名长度
     *
     * @param string $username
     * @return boolean
     */
    public function check_username_length($username) {
        $len = Utility::strlen($username);
        if ($len < $this->_config['min_username_length'] or $len > $this->_config['max_username_length']) {
            return false;
        }
        return true;
    }

    /**
     * 检查用户名的格式
     * 不能有空格，只支持中文、字母、数字、下划线和小数点
     *
     * @param string $username
     * @return boolean
     */
    public function check_username_format($username) {
        return $this->form_validation->alpha_zh($username);
    }

    /**
     * 检查用户名是否禁用
     *
     * @param string $username
     * @return boolean
     */
    public function check_username_ban($username) {
        $ban_username = explode(',', $this->_config['ban_username']);
        return str_replace($ban_username, '', $username) == $username;
    }

    /**
     * 验证密码
     *
     * @param string $password
     * @param string $username
     * @return boolean
     */
    public function check_password($password, $username) {
        //密码长度是否错误
        if (!$this->check_password_length($password)) {
            $min = $this->_config['min_password_length'];
            return $this->error->set_error('AUTH:password_length_error', array('min' => $min));
        }
        //密码复杂度检查
        if (!$this->check_password_complex($password, $username)) {
            return false;
        }

        return true;
    }

    /**
     * 检查密码长度
     *
     * @param string $password
     * @return boolean
     */
    public function check_password_length($password) {
        $password = str_replace(array(' ', '　', '	'), '', $password);
        $len = Utility::strlen($password);
        if ($len < $this->_config['min_password_length']) {
            return false;
        }
        return true;
    }

    /**
     * 验证密码的复杂度是否符合后台设置要求
     * 检查密码复杂度
     * 检查用户名和密码是否允许相同
     * 如果设置不允许相同而相同则返回PwError
     * 其余返回true
     *
     * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com>
     * @param string $password 用户密码
     * @param string $username 用户名
     * @return boolean
     */
    public function check_password_complex($password, $username) {
        $_complex = $this->_config['password_security'];
        if (!$_complex) return true;
        $config = array_sum($_complex);
        if (in_array(9, $_complex)) {
            $config = $config - 9;
            if ($username == $password) {
                return $this->error->set_error('AUTH:password_equal_username');
            }
        }
        if ($config == 0) return true;
        if (self::_complex_caculate($password, $config)) {
            return $this->error->set_error('AUTH:password_complex_error', array('type' => self::build_password_complex_msg($_complex)));
        }

        return true;
    }

    /**
     * 显示用户密码的支持信息
     *
     * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com>
     * @return array(string, args)
     */
    public function build_pwd_show_msg() {
        $_min = $this->_config['min_password_length'];
        $_complex = $this->_config['password_security'];
        $_length = $_min;
        $type = self::build_password_complex_msg($_complex);
        $var = array();
        $_key = 'password_require';
        if ($_length && $_complex) {
            $_key = 'password_format_require';
            $var = array('type' => $type, 'min' => $_min);
        } elseif (!$_complex && $_length) {
            $_key = 'password_length_error';
            $var = array('min' => $_min);
        } elseif (!$_length && $_complex) {
            $_key = 'password_complex_error';
            $var = array('type' => $type);
        }
        return array($_key, $var);
    }

    /**
     * 构造用户密码复杂度的校验规则
     *
     * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com>
     * @param array $config 复杂规则的配置
     * @return string
     */
    private static function build_password_complex_msg($config) {
        if (!$config) return '';
        $complex = array(1 => '小写字母', 2 => '大写字母', 4 => '数字', 8 => '符号', 9 => '不能和用户名相同');
        return implode('、', array_intersect_key($complex, array_flip($config)));
    }

    /**
     * 复杂度判断
     *
     * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com>
     * @param string $password 密码
     * @param int $config 配置
     * @return boolean
     */
    private static function _complex_caculate($password, $config) {
        $pwdLen = strlen($password);
        $complex = 0;
        for ($i = 0; $i < $pwdLen; $i++) {
            $ascii = ord($password[$i]);
            //必须含有小写字母 97-122
            if (1 == ($config & 1) && $ascii >= 97 && $ascii <= 122) {
                if (0 == $complex || 1 != ($complex & 1)) $complex += 1;
                continue;
            }
            //必须含有大写字母 65-90
            if (2 == ($config & 2) && $ascii >= 65 && $ascii <= 90) {
                if (0 == $complex || 2 != ($complex & 2)) $complex += 2;
                continue;
            }
            //必须含有数字 48-57
            if (4 == ($config & 4) && $ascii >= 48 && $ascii <= 57) {
                if (0 == $complex || 4 != ($complex & 4)) $complex += 4;
                continue;
            }
            //必须含有符号 33-47/58-64/91-96/123-126
            if (8 == ($config & 8) && (($ascii >= 33 && $ascii <= 47) || ($ascii >= 58 && $ascii <= 64) || ($ascii >= 91 && $ascii <= 96) || ($ascii >= 123 && $ascii <= 126))) {
                if (0 == $complex || 8 != ($complex & 8)) $complex += 8;
                continue;
            }
            //已经达到设置复杂度则跳出
            if ($config == $complex) break;
        }
        return $config != $complex;
    }

    /**
     * 判断获得密码强度等级
     *
     * @author xiaoxia.xu <xiaoxia.xuxx@aliyun-inc.com>
     * @param string $pwd 密码强度
     * @return int 返回强度级别：(1：弱,2: 一般, 3： 强, 4：非常强)
     */
    public static function check_password_strong($pwd) {
        $array = array();
        $len = strlen($pwd);
        $i = 0;
        $mode = array('a' => 0, 'A' => 0, 'd' => 0, 'f' => 0);
        while ($i < $len) {
            $ascii = ord($pwd[$i]);
            if ($ascii >= 48 && $ascii <= 57) //数字
                $mode['d']++; elseif ($ascii >= 65 && $ascii <= 90) //大写字母
                $mode['A']++;
            elseif ($ascii >= 97 && $ascii <= 122) //小写
                $mode['a']++;
            else  $mode['f']++;
            $i++;
        }
        /*全是小写字母或是大写字母或是字符*/
        if ($mode['a'] == $len || $mode['A'] == $len || $mode['f'] == $len) {
            return 2;
        }
        /*全是数字*/
        if ($mode['d'] == $len) {
            return 1;
        }

        $score = 0;
        /*大小写混合得分20分*/
        if ($mode['a'] > 0 && $mode['A'] > 0) {
            $score += 20;
        }
        /*如果含有3个以内（不包含0和3）数字得分10分,如果包括3个（含3个）以上得分20*/
        if ($mode['d'] > 0 && $mode['d'] < 3) {
            $score += 10;
        } elseif ($mode['d'] >= 3) {
            $score += 20;
        }
        /*如果含有一个字符得分10分，含有1个以上字符得分25*/
        if ($mode['f'] == 1) {
            $score += 10;
        } elseif ($mode['f'] > 1) {
            $score += 25;
        }
        /*同时含有：字母和数字 得25分；含有：字母、数字和符号 得30分；含有：大小写字母、数字和符号 得35分*/
        if ($mode['a'] > 0 && $mode['A'] > 0 && $mode['d'] > 0 && $mode['f'] > 0) {
            $score += 35;
        } elseif (($mode['a'] > 0 || $mode['A'] > 0) && $mode['d'] > 0 && $mode['f'] > 0) {
            $score += 30;
        } elseif (($mode['a'] > 0 || $mode['A'] > 0) && $mode['d'] > 0) {
            $score += 25;
        }
        if ($len < 3) $score -= 10;
        if ($score >= 60) {
            return 4;
        } elseif ($score >= 40) {
            return 3;
        } elseif ($score >= 20) {
            return 2;
        }
        return 1;
    }

    /**
     * 验证Email
     *
     * @param string $email
     * @return boolean
     */
    public function check_email($email) {
        //Email格式验证
        if (!$this->check_email_format($email)) {
            return $this->error->set_error('AUTH:email_error');
        }

        //UC检查用户名
        if ($this->_config['enable_ucenter']) {
            $this->load->library('uc/uc_api');
            $uc_result = $this->uc_api->user_checkemail($email);
            if ($uc_result == -4) {
                return $this->error->set_error('AUTH:email_error');
            } elseif ($uc_result == -5) {
                return $this->error->set_error('AUTH:email_cannot_be_used');
            } elseif ($uc_result == -6) {
                return $this->error->set_error('AUTH:email_already_exists');
            }
        }

        return true;
    }

    /**
     * 检查Email格式
     *
     * @param string $email
     * @return boolean
     */
    public function check_email_format($email) {
        return $this->form_validation->valid_email($email);
    }

    /**
     * 发送激活邮件
     *
     * @param string $username 用户名
     * @param string $email 用户邮件
     * @param string $statu 激活标志
     * @param int $uid 用户ID
     * @return boolean
     */
    public function send_activation_email($username, $email, $statu, $uid) {
        $data = array();
        $data['identity'] = '';
        $data['uid'] = '';
        $data['email'] = '';
        $data['activation_code'] = '';

        $this->load->library('email');
        $this->email->clear();
        $this->email->from('admin@admin.com', '网站标题');
        $this->email->to('52371354@qq.com');
        $this->email->subject('网站标题 - 帐号激活');
        $this->email->message('激活内容');

        $this->email->send();
        return true;
    }

    ################################ 模型 ################################

    /**
     * 获取用户基本信息
     *
     * @param $field 查找字段
     * @param $value 查找的值
     * @return array
     */
    public function get_user_by($field, $value) {
        $fields = array('uid', 'username', 'email');
        if (!in_array($field, $fields)) return array();

        $this->db->where($field, $value);
        return $this->db->get($this->_config['tables']['user'], 1)->row_array();
    }

    /**
     * 更新登陆记录
     *
     * @param array $user
     * @return boolean
     */
    public function update_last_login($user) {
        $save = array('last_login_time' => TIMESTAMP, 'last_login_ip' => $this->input->ip_address());
        $this->db->update('user_data', $save, array('uid' => $user['uid']));
        return $this->db->affected_rows() == 1;
    }

    /**
     * 获取当前尝试登陆次数
     *
     * @return    int
     */
    public function get_login_attempt_num() {
        $where = array('ip_address' => $this->input->ip_address(), 'type' => 'login');
        $query = $this->db->get_where($this->_config['tables']['security'], $where, 1);
        return $query->num_rows() > 0 ? $query->row()->num : 0;
    }

    /**
     * 获取最后一次尝试登陆时间
     *
     * @return    int
     */
    public function get_last_login_attempt_time() {
        $where = array('ip_address' => $this->input->ip_address(), 'type' => 'login');
        $this->db->select_max('last_time');
        $query = $this->db->get_where($this->_config['tables']['security'], $where, 1);
        return $query->num_rows() > 0 ? $query->row()->last_time : 0;
    }

    /**
     * 增加尝试登陆记录
     *
     * @return bool
     */
    public function increase_login_attempt() {
        $table = $this->_config['tables']['security'];
        $where = array('ip_address' => $this->input->ip_address(), 'type' => 'login');
        $query = $this->db->get_where($table, $where);

        $save = array();
        $save['ip_address'] = $this->input->ip_address();
        $save['type'] = 'login';
        $save['last_time'] = TIMESTAMP;
        $save['num'] = $query->num_rows() ? $query->row()->num + 1 : 1;

        if ($query->num_rows()) {
            return $this->db->update($table, $save, $where);
        } else {
            return $this->db->insert($table, $save);
        }
    }

    /**
     * 清除登陆尝试记录
     * 登陆成功后清除登陆记录 并 清除过期后的记录
     *
     * @param int $expiration_time 过期时间
     * @return bool
     */
    public function clear_login_attempt($expiration_time = 86400) {
        $where = array('ip_address' => $this->input->ip_address(), 'type' => 'login');
        $orwhere = array('last_time < ' => TIMESTAMP - $expiration_time, 'type' => 'login');
        $this->db->where($where)->or_where($orwhere);
        return $this->db->delete($this->_config['tables']['security']);
    }

    /**
     * 获取注册次数和最后注册时间
     *
     * @return    int
     */
    public function get_register_security() {
        $where = array('ip_address' => $this->input->ip_address(), 'type' => 'register');
        $query = $this->db->get_where($this->_config['tables']['security'], $where, 1);
        return $query->num_rows() ? $query->row_array() : array();
    }

    /**
     * 增加注册记录
     *
     * @return bool
     */
    public function increase_register_security() {
        $save = array();
        $save['ip_address'] = $this->input->ip_address();
        $save['type'] = 'register';
        $save['last_time'] = TIMESTAMP;
        $save['num'] = 1;

        $table = $this->db->protect_identifiers($this->_config['tables']['security'], true);

        $sql = 'REPLACE INTO ' . $table;
        $sql .= ' SET `ip_address` = ?, `type` = ?, `last_time` = ?, `num` = ?';
        return $this->db->query($sql, $save);
    }

    /**
     * 清除过期同一IP注册次数限制
     */
    public function clear_register_security() {
        $hour = $this->_config['register_limit_hour'];
        $where = array('last_time < ' => TIMESTAMP - $hour * 3600, 'type' => 'register');
        return $this->db->delete($this->_config['tables']['security'], $where);
    }

    /**
     * Email是否存在
     *
     * @param string $email
     * @return boolean
     */
    public function is_email_exist($email) {
        $table = $this->_config['tables']['user'];
        return $this->db->where('email', $email)->count_all_results($table) > 0;
    }

    /**
     * Username是否存在
     *
     * @param string $username
     * @return boolean
     */
    public function is_username_exist($username) {
        $table = $this->_config['tables']['user'];
        return $this->db->where('username', $username)->count_all_results($table) > 0;
    }

    /**
     * 添加用户
     *
     * @param int $uid
     * @param string $username
     * @param string $password
     * @param string $email
     * @return int $uid
     */
    public function add_user($uid = null, $username, $password, $email) {
        $save = array();
        $save['uid'] = $uid > 0 ? $uid : null;
        $save['username'] = $username;
        $save['salt'] = $this->salt();
        $save['password'] = $this->hash_password($password, $save['salt']);
        $save['email'] = $email;
        $save['gid'] = $this->get_default_group();

        $table = $this->db->protect_identifiers($this->_config['tables']['user'], true);

        $sql = "REPLACE INTO {$table} ";
        $sql .= "SET `uid` = ?, `username` = ?, `salt` = ?, `password` = ?, `email` = ?, `gid` = ?";
        $this->db->query($sql, $save);
        return $this->db->insert_id();
    }

    /**
     * 添加用户数据表（用户扩展表一）
     *
     * @param int $uid
     * @return int $uid
     */
    public function add_user_data($uid) {
        $save = array();
        $save['uid'] = $uid;
        $save['last_login_time'] = TIMESTAMP;
        $save['last_login_ip'] = $this->input->ip_address();

        $table = $this->db->protect_identifiers($this->_config['tables']['user_data'], true);

        $sql = 'REPLACE INTO ' . $table;
        $sql .= ' SET `uid` = ?, `last_login_time` = ?, `last_login_ip` = ?';
        $this->db->query($sql, $save);
        return $uid;
    }

    /**
     * 添加用户数据表（用户扩展表一）
     *
     * @param int $uid
     * @return int $uid
     */
    public function add_user_info($uid) {
        $save = array();
        $save['uid'] = $uid;
        $save['signature'] = ''; //个性签名必须有默认值
        $save['profile'] = ''; //个人简介必须有默认值
        $table = $this->db->protect_identifiers($this->_config['tables']['user_info'], true);
        $sql = 'REPLACE INTO ' . $table;
        $sql .= ' SET `uid` = ?, `signature` = ?, `profile` = ?';
        $this->db->query($sql, $save);
        return $uid;
    }

    /**
     * 获取默认用户组id
     */
    public function get_default_group() {
        $email_activation = $this->_config['email_activation'];
        //注册激活用户默认用户组
        $activation_gid = $this->_config['default_group_activation'];
        //注册未激活用户默认用户组
        $unactivation_gid = $this->_config['default_group_unactivation'];

        return $email_activation ? $unactivation_gid : $activation_gid;
    }

    ################################ 其他 ################################

    /**
     * 创建用户注册标志
     *
     * @param int $uid 用户ID
     * @param string $pwd 用户密码
     * @return string
     */
    public function create_regist_identify($uid, $pwd) {
        $code = Utility::encode($uid . "\t" . Utility::get_pwd_code($pwd));
        return rawurlencode($code);
    }

    /**
     * 解析用户注册标志
     *
     * @param string $identify
     * @return array array($uid, $password);
     */
    public function parser_regist_identify($identify) {
        return explode("\t", Utility::decode(rawurldecode($identify)));
    }

    /**
     * 加密密码
     *
     * @param string $password 用户登录的密码
     * @param string $salt 盐值
     * @return string
     */
    public function hash_password($password, $salt = '') {
        return md5(md5($password) . $salt);
    }

    /**
     * 生成盐值
     */
    public function salt() {
        return substr(md5(md5(uniqid())), 0, 6);
    }

}

/* End of file user_auth_service.php */
/* Location: ./application/service/user/user_auth_service.php */
